package com.gx.rabbit.config;


import com.gx.common.constant.RabbitMqConstant;
import com.gx.rabbit.consumer.DirectConsumer;
import org.springframework.amqp.core.*;
import org.springframework.amqp.rabbit.connection.ConnectionFactory;
import org.springframework.amqp.rabbit.listener.SimpleMessageListenerContainer;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.amqp.RabbitProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

/**
 * @Author Liu-pj
 * @Date 2023/3/9 15:31
 * @Desc 用户信息新增 Direct路由模式
 **/
@Configuration

public class DirectConf {

    private final RabbitProperties rabbitProperties;

    public DirectConf(RabbitProperties rabbitProperties) {
        this.rabbitProperties = rabbitProperties;
    }

    /**
     * 创建交换机
     *
     * @return 交换机
     */
    @Bean
    public DirectExchange exchangeUserCreate() {
        return new DirectExchange(RabbitMqConstant.DIRECT_EXCHANGE_USER_CREATE);
    }

    /**
     * 创建队列
     *
     * @return
     */
    @Bean
    public Queue queueUserCreate() {
        return QueueBuilder.durable(RabbitMqConstant.DIRECT_QUERY_USER_CREATE)
                .build();
    }


    @Bean
    public Binding userCreateExBindingUserCreateQueue() {
        return BindingBuilder.bind(queueUserCreate())
                .to(exchangeUserCreate())
                .with(RabbitMqConstant.DIRECT_ROUTING_USER_CREATE);
    }

    @Bean
    public SimpleMessageListenerContainer userCreateConsumerListenerContainer(ConnectionFactory connectionFactory,
                                                                              @Qualifier("directConsumer") DirectConsumer directConsumer) {
        SimpleMessageListenerContainer container = new SimpleMessageListenerContainer(connectionFactory);
        container.setQueueNames(RabbitMqConstant.DIRECT_QUERY_USER_CREATE);
        buildMessageListenerContainer(container);
        container.setMessageListener(directConsumer);
        return container;
    }

    private void buildMessageListenerContainer(SimpleMessageListenerContainer messageListenerContainer) {
        messageListenerContainer.setExposeListenerChannel(true);
        messageListenerContainer.setAcknowledgeMode(rabbitProperties.getListener().getSimple().getAcknowledgeMode());
        messageListenerContainer.setPrefetchCount(rabbitProperties.getListener().getSimple().getPrefetch());
        messageListenerContainer.setConcurrentConsumers(rabbitProperties.getListener().getSimple().getConcurrency());
        messageListenerContainer.setMaxConcurrentConsumers(rabbitProperties.getListener().getSimple().getMaxConcurrency());
    }
}
